package com.atguigu.tingshu.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.atguigu.tingshu.payment.util.PayUtil;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

	@Resource
	private PaymentInfoService paymentInfoService;

    @Resource
    private RSAAutoCertificateConfig config;

    @Resource
    private WxPayV3Config wxPayV3Config;

    @Resource
    private UserInfoFeignClient userInfoFeignClient;

    @Resource
    private OrderInfoFeignClient orderInfoFeignClient;

    @Override
    public Map<String,Object> createJsapi(String paymentType, String orderNo, Long userId) {
        try {
            //	根据业务判断类型：
            //	充值业务不需要判断当前订单是否取消
            if (!paymentType.equals(SystemConstant.PAYMENT_TYPE_RECHARGE)){
                //	查询当前订单状态，如果订单状态已经取消，则不能生成二维码！
                Result<OrderInfo> orderInfoResult = this.orderInfoFeignClient.getOrderInfo(orderNo);
                OrderInfo orderInfo = orderInfoResult.getData();
                if (SystemConstant.ORDER_STATUS_CANCEL.equals(orderInfo.getOrderStatus())){
                    //	此时订单已取消，不能生成二维码！
                    return null;
                }
            }
            // 保存支付记录
            PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(paymentType, orderNo);
            //	构建service
            JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();
            PrepayRequest request = new PrepayRequest();
            // 注意在这个包下 com.wechat.pay.java.service.payments.jsapi.model.Amount
            Amount amount = new Amount();
            amount.setTotal(1);
            request.setAmount(amount);
            request.setAppid(wxPayV3Config.getAppid());
            request.setMchid(wxPayV3Config.getMerchantId());
            request.setDescription(paymentInfo.getContent());
            request.setNotifyUrl(wxPayV3Config.getNotifyUrl());
            request.setOutTradeNo(paymentInfo.getOrderNo());
            //	获取用户信息
            Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVo(paymentInfo.getUserId());
            Assert.notNull(userInfoVoResult,"返回用户结果集对象不能为空");
            UserInfoVo userInfoVo = userInfoVoResult.getData();
            Assert.notNull(userInfoVo,"用户对象不能为空");
            String openid = userInfoVo.getWxOpenId();
            Payer payer = new Payer();
            payer.setOpenid(openid);
            request.setPayer(payer);

            // 调用下单方法，得到应答
            // response包含了调起支付所需的所有参数，可直接用于前端调起支付
            PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
            log.info("微信支付下单返回参数：{}", JSON.toJSONString(response));
            Map<String, Object> result = new HashMap();
            result.put("timeStamp", response.getTimeStamp());
            result.put("nonceStr", response.getNonceStr());
            result.put("package", response.getPackageVal());
            result.put("signType", response.getSignType());
            result.put("paySign", response.getPaySign());
            //	返回数据
            return result;
        } catch (GuiguException e){
            e.printStackTrace();
            throw  new GuiguException(201,e.getMessage());
        } catch (Exception e){
            e.printStackTrace();
            throw new GuiguException(201,"微信下单异常");
        }
    }

    @Override
    public Transaction queryPayStatus(String orderNo) {
        try {
            //	构建service
            JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();
            QueryOrderByOutTradeNoRequest queryRequest = new QueryOrderByOutTradeNoRequest();
            queryRequest.setMchid(wxPayV3Config.getMerchantId());
            queryRequest.setOutTradeNo(orderNo);

            Transaction result = service.queryOrderByOutTradeNo(queryRequest);
            log.info("Transaction:\t"+JSON.toJSONString(result));
            return result ;
        } catch (ServiceException e){
            // API返回失败, 例如ORDER_NOT_EXISTS
            System.out.printf("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
            System.out.printf("reponse body=[%s]\n", e.getResponseBody());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void wxnotify(HttpServletRequest request) {
        //1.回调通知的验签与解密
        //从request头信息获取参数
        //HTTP 头 Wechatpay-Signature
        // HTTP 头 Wechatpay-Nonce
        //HTTP 头 Wechatpay-Timestamp
        //HTTP 头 Wechatpay-Serial
        //HTTP 头 Wechatpay-Signature-Type
        //HTTP 请求体 body。切记使用原始报文，不要用 JSON 对象序列化后的字符串，避免验签的 body 和原文不一致。
        String wechatPaySerial = request.getHeader("Wechatpay-Serial");
        String nonce = request.getHeader("Wechatpay-Nonce");
        String timestamp = request.getHeader("Wechatpay-Timestamp");
        String signature = request.getHeader("Wechatpay-Signature");
        // 调用工具类来获取请求体数据
        String requestBody = PayUtil.readData(request);

        //2.构造 RequestParam
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(wechatPaySerial)
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                .body(requestBody)
                .build();

        //3.初始化 NotificationParser
        NotificationParser parser = new NotificationParser(config);
        //4.以支付通知回调为例，验签、解密并转换成 Transaction
        Transaction transaction = parser.parse(requestParam, Transaction.class);
        log.info("成功解析：{}", JSON.toJSONString(transaction));
        if(null != transaction && transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {
            // 5.处理支付业务
            paymentInfoService.updatePaymentStatus(transaction);
        }
    }
}
